use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{Mutex, broadcast};
use tracing::{info, error, debug, warn};
use chrono::{DateTime, Utc};

use super::{AdbManager, AdbError, DeviceInfo, DeviceStatus, PerformanceMetrics};

/// 设备管理器事件
#[derive(Debug, Clone)]
pub enum DeviceEvent {
    DeviceAdded(DeviceInfo),
    DeviceRemoved(String),
    DeviceStatusChanged(String, DeviceStatus),
    DeviceHealthUpdated(String, DeviceHealth),
    ScanCompleted(usize),
    Error(String, String),
}

/// 设备健康状态
#[derive(Debug, Clone)]
pub struct DeviceHealth {
    pub device_id: String,
    pub is_healthy: bool,
    pub performance: PerformanceMetrics,
    pub last_check: DateTime<Utc>,
    pub issues: Vec<String>,
}

/// 统一设备管理器
pub struct DeviceManager {
    adb_manager: Arc<Mutex<AdbManager>>,
    devices: Arc<Mutex<HashMap<String, DeviceInfo>>>,
    health_monitors: Arc<Mutex<HashMap<String, DeviceHealth>>>,
    event_sender: broadcast::Sender<DeviceEvent>,
    monitoring_active: Arc<Mutex<bool>>,
}

impl DeviceManager {
    /// 创建设备管理器实例
    pub async fn new() -> Result<Self, AdbError> {
        info!("Initializing Device Manager");
        
        let adb_manager = AdbManager::new().await?;
        let (event_sender, _) = broadcast::channel(200);
        
        Ok(DeviceManager {
            adb_manager: Arc::new(Mutex::new(adb_manager)),
            devices: Arc::new(Mutex::new(HashMap::new())),
            health_monitors: Arc::new(Mutex::new(HashMap::new())),
            event_sender,
            monitoring_active: Arc::new(Mutex::new(false)),
        })
    }

    /// 启动设备管理器
    pub async fn start(&self) -> Result<(), AdbError> {
        info!("Starting Device Manager");
        
        // 启动ADB心跳监控
        {
            let adb_manager = self.adb_manager.lock().await;
            adb_manager.start_heartbeat_monitor().await;
        }
        
        // 启动健康监控
        self.start_health_monitoring().await;
        
        // 初始设备扫描
        self.scan_devices().await?;
        
        info!("Device Manager started successfully");
        Ok(())
    }

    /// 扫描所有设备
    pub async fn scan_devices(&self) -> Result<Vec<DeviceInfo>, AdbError> {
        info!("Scanning for all devices");
        
        let adb_manager = self.adb_manager.lock().await;
        let adb_devices = adb_manager.scan_devices().await?;
        
        // 更新本地设备列表
        {
            let mut devices = self.devices.lock().await;
            devices.clear();
            
            for device in &adb_devices {
                devices.insert(device.id.clone(), device.clone());
                
                // 发送设备添加事件
                let _ = self.event_sender.send(DeviceEvent::DeviceAdded(device.clone()));
            }
        }
        
        // 发送扫描完成事件
        let _ = self.event_sender.send(DeviceEvent::ScanCompleted(adb_devices.len()));
        
        info!("Device scan completed, found {} devices", adb_devices.len());
        Ok(adb_devices)
    }

    /// 连接设备
    pub async fn connect_device(&self, device_id: &str) -> Result<(), AdbError> {
        info!("Connecting device through manager: {}", device_id);
        
        let adb_manager = self.adb_manager.lock().await;
        let result = adb_manager.connect_device(device_id).await;
        
        if result.is_ok() {
            // 更新本地设备状态
            let mut devices = self.devices.lock().await;
            if let Some(device) = devices.get_mut(device_id) {
                device.status = DeviceStatus::Online;
                device.last_heartbeat = Some(Utc::now());
                
                // 发送状态变更事件
                let _ = self.event_sender.send(DeviceEvent::DeviceStatusChanged(
                    device_id.to_string(),
                    DeviceStatus::Online,
                ));
            }
        }
        
        result
    }

    /// 断开设备连接
    pub async fn disconnect_device(&self, device_id: &str) -> Result<(), AdbError> {
        info!("Disconnecting device through manager: {}", device_id);
        
        let adb_manager = self.adb_manager.lock().await;
        let result = adb_manager.disconnect_device(device_id).await;
        
        if result.is_ok() {
            // 更新本地设备状态
            let mut devices = self.devices.lock().await;
            if let Some(device) = devices.get_mut(device_id) {
                device.status = DeviceStatus::Offline;
                
                // 发送状态变更事件
                let _ = self.event_sender.send(DeviceEvent::DeviceStatusChanged(
                    device_id.to_string(),
                    DeviceStatus::Offline,
                ));
            }
            
            // 移除健康监控
            let mut health_monitors = self.health_monitors.lock().await;
            health_monitors.remove(device_id);
        }
        
        result
    }

    /// 获取设备截图
    pub async fn take_device_screenshot(&self, device_id: &str) -> Result<Vec<u8>, AdbError> {
        let adb_manager = self.adb_manager.lock().await;
        adb_manager.take_screenshot(device_id).await
    }

    /// 获取设备性能指标
    pub async fn get_device_performance(&self, device_id: &str) -> Result<PerformanceMetrics, AdbError> {
        let adb_manager = self.adb_manager.lock().await;
        adb_manager.get_performance_metrics(device_id).await
    }

    /// 获取设备健康状态
    pub async fn get_device_health(&self, device_id: &str) -> Result<Option<DeviceHealth>, AdbError> {
        let health_monitors = self.health_monitors.lock().await;
        Ok(health_monitors.get(device_id).cloned())
    }

    /// 获取所有设备
    pub async fn get_all_devices(&self) -> Result<Vec<DeviceInfo>, AdbError> {
        let devices = self.devices.lock().await;
        Ok(devices.values().cloned().collect())
    }

    /// 获取设备详情
    pub async fn get_device_details(&self, device_id: &str) -> Result<DeviceInfo, AdbError> {
        let devices = self.devices.lock().await;
        devices.get(device_id)
            .cloned()
            .ok_or_else(|| AdbError::DeviceNotFound(device_id.to_string()))
    }

    /// 订阅设备事件
    pub fn subscribe_events(&self) -> broadcast::Receiver<DeviceEvent> {
        self.event_sender.subscribe()
    }

    /// 启动健康监控
    async fn start_health_monitoring(&self) {
        info!("Starting device health monitoring");
        
        let devices = self.devices.clone();
        let health_monitors = self.health_monitors.clone();
        let event_sender = self.event_sender.clone();
        let monitoring_active = self.monitoring_active.clone();
        let adb_manager = self.adb_manager.clone();
        
        // 设置监控为活跃状态
        *monitoring_active.lock().await = true;
        
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));
            
            loop {
                interval.tick().await;
                
                // 检查监控是否仍然活跃
                {
                    let active = monitoring_active.lock().await;
                    if !*active {
                        break;
                    }
                }
                
                // 获取在线设备列表
                let online_devices: Vec<String> = {
                    let devices_guard = devices.lock().await;
                    devices_guard
                        .values()
                        .filter(|device| matches!(device.status, DeviceStatus::Online))
                        .map(|device| device.id.clone())
                        .collect()
                };
                
                // 为每个在线设备检查健康状态
                for device_id in online_devices {
                    if let Err(e) = Self::check_device_health(
                        &device_id,
                        &adb_manager,
                        &health_monitors,
                        &event_sender,
                    ).await {
                        warn!("Health check failed for device {}: {}", device_id, e);
                    }
                }
            }
            
            info!("Health monitoring stopped");
        });
    }

    /// 检查单个设备健康状态
    async fn check_device_health(
        device_id: &str,
        adb_manager: &Arc<Mutex<AdbManager>>,
        health_monitors: &Arc<Mutex<HashMap<String, DeviceHealth>>>,
        event_sender: &broadcast::Sender<DeviceEvent>,
    ) -> Result<(), AdbError> {
        debug!("Checking health for device: {}", device_id);
        
        let performance = {
            let adb = adb_manager.lock().await;
            adb.get_performance_metrics(device_id).await?
        };
        
        // 分析健康状态
        let mut issues = Vec::new();
        let mut is_healthy = true;
        
        // CPU使用率检查
        if performance.cpu_usage > 80.0 {
            issues.push("CPU usage too high".to_string());
            is_healthy = false;
        }
        
        // 内存使用率检查
        if performance.memory_usage > 90.0 {
            issues.push("Memory usage critical".to_string());
            is_healthy = false;
        }
        
        // 电池电量检查
        if let Some(battery) = performance.battery_level {
            if battery < 15.0 {
                issues.push("Low battery level".to_string());
                is_healthy = false;
            }
        }
        
        let health = DeviceHealth {
            device_id: device_id.to_string(),
            is_healthy,
            performance,
            last_check: Utc::now(),
            issues,
        };
        
        // 更新健康监控记录
        {
            let mut monitors = health_monitors.lock().await;
            monitors.insert(device_id.to_string(), health.clone());
        }
        
        // 发送健康状态更新事件
        let _ = event_sender.send(DeviceEvent::DeviceHealthUpdated(
            device_id.to_string(),
            health,
        ));
        
        Ok(())
    }

    /// 停止监控
    pub async fn stop_monitoring(&self) {
        info!("Stopping device monitoring");
        *self.monitoring_active.lock().await = false;
    }

    /// 批量连接设备
    pub async fn batch_connect(&self, device_ids: Vec<String>) -> Result<HashMap<String, Result<(), String>>, AdbError> {
        info!("Batch connecting {} devices", device_ids.len());
        
        let mut results = HashMap::new();
        
        // 并发连接设备
        let tasks: Vec<_> = device_ids.iter().map(|device_id| {
            let manager = self.adb_manager.clone();
            let id = device_id.clone();
            
            tokio::spawn(async move {
                let adb = manager.lock().await;
                match adb.connect_device(&id).await {
                    Ok(_) => (id, Ok(())),
                    Err(e) => (id, Err(e.to_string())),
                }
            })
        }).collect();
        
        for task in tasks {
            if let Ok((device_id, result)) = task.await {
                results.insert(device_id, result.map_err(|e| e.to_string()));
            }
        }
        
        Ok(results)
    }

    /// 批量断开设备
    pub async fn batch_disconnect(&self, device_ids: Vec<String>) -> Result<HashMap<String, Result<(), String>>, AdbError> {
        info!("Batch disconnecting {} devices", device_ids.len());
        
        let mut results = HashMap::new();
        
        for device_id in device_ids {
            match self.disconnect_device(&device_id).await {
                Ok(_) => {
                    results.insert(device_id, Ok(()));
                }
                Err(e) => {
                    results.insert(device_id, Err(e.to_string()));
                }
            }
        }
        
        Ok(results)
    }

    /// 获取管理器统计信息
    pub async fn get_manager_stats(&self) -> Result<serde_json::Value, AdbError> {
        let devices = self.devices.lock().await;
        let health_monitors = self.health_monitors.lock().await;
        
        let total_devices = devices.len();
        let online_devices = devices.values()
            .filter(|d| matches!(d.status, DeviceStatus::Online))
            .count();
        let healthy_devices = health_monitors.values()
            .filter(|h| h.is_healthy)
            .count();
        
        let stats = serde_json::json!({
            "total_devices": total_devices,
            "online_devices": online_devices,
            "offline_devices": total_devices - online_devices,
            "healthy_devices": healthy_devices,
            "monitoring_active": *self.monitoring_active.lock().await,
            "last_scan": Utc::now().to_rfc3339(),
        });
        
        Ok(stats)
    }
}